package io.yuncheng.modules.sys.controller;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.yuncheng.common.config.DictConfig;
import io.yuncheng.common.utils.*;
import io.yuncheng.modules.sys.entity.*;
import io.yuncheng.modules.sys.service.SubAppLogCollectService;
import io.yuncheng.modules.sys.service.SubApplicationService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.yuncheng.common.utils.DateUtils;
import io.yuncheng.common.utils.NumberUtil;
import io.yuncheng.common.utils.SysDictConstant;
import io.yuncheng.modules.sys.entity.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import io.yuncheng.modules.sys.service.SubAppAlgorithmLogCollectPathService;

import javax.annotation.Resource;


/**
 * 算法日志链路汇总
 *
 * @author jared
 * @email 15721509625@163.com2
 * @date 2020-10-29 21:14:27
 */
@RestController
@Api(tags = "密码路径统计")
@RequestMapping("sys/subappalgorithmlogcollectpath")
public class SubAppAlgorithmLogCollectPathController {
    @Autowired
    private SubAppAlgorithmLogCollectPathService subAppAlgorithmLogCollectPathService;
    @Resource
    private SubAppLogCollectService subAppLogCollectService;
    @Autowired
    private SubApplicationService subApplicationService;
    @Resource
    private DictConfig dictConfig;

    /**
     * 列表
     */
    @PostMapping("/list")
    @RequiresPermissions("sys:subappalgorithmlogcollectpath:list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = subAppAlgorithmLogCollectPathService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @GetMapping("/info/{id}")
    @RequiresPermissions("sys:subappalgorithmlogcollectpath:info")
    public R info(@PathVariable("id") Long id){
		SubAppAlgorithmLogCollectPathEntity subAppAlgorithmLogCollectPath = subAppAlgorithmLogCollectPathService.getById(id);

        return R.ok().put("subAppAlgorithmLogCollectPath", subAppAlgorithmLogCollectPath);
    }

    /**
     * 保存
     */
    @PostMapping("/save")
    @RequiresPermissions("sys:subappalgorithmlogcollectpath:save")
    public R save(@RequestBody SubAppAlgorithmLogCollectPathEntity subAppAlgorithmLogCollectPath){
		subAppAlgorithmLogCollectPathService.save(subAppAlgorithmLogCollectPath);

        return R.ok();
    }

    /**
     * 修改
     */
    @PostMapping("/update")
    @RequiresPermissions("sys:subappalgorithmlogcollectpath:update")
    public R update(@RequestBody SubAppAlgorithmLogCollectPathEntity subAppAlgorithmLogCollectPath){
		subAppAlgorithmLogCollectPathService.updateById(subAppAlgorithmLogCollectPath);

        return R.ok();
    }

    /**
     * 删除
     */
    @PostMapping("/delete")
    @RequiresPermissions("sys:subappalgorithmlogcollectpath:delete")
    public R delete(@RequestBody Long[] ids){
		subAppAlgorithmLogCollectPathService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }


    /**
     * 列表
     */
    @PostMapping("/list-collect-old")
    @ApiOperation("查询链路场景")
    public R collectByDate(Long deptId, Date start,Date end){
        SubApplicationEntity subApplicationEntity = subApplicationService.queryByDeptId(deptId);
        QueryWrapper<SubAppAlgorithmLogCollectPathEntity> query = new QueryWrapper<SubAppAlgorithmLogCollectPathEntity>().ge("log_date",start).lt("log_date",end).eq("app_id",subApplicationEntity.getAppId());
        List<SubAppAlgorithmLogCollectPathEntity> list = subAppAlgorithmLogCollectPathService.list(query);
        Long all = list.stream().mapToLong(SubAppAlgorithmLogCollectPathEntity::getAlgorithmTimeOne).sum();
        Map<String, LongSummaryStatistics> mapList = list.stream().collect(Collectors.groupingBy(SubAppAlgorithmLogCollectPathEntity::getAlgorithmPath, Collectors.summarizingLong(SubAppAlgorithmLogCollectPathEntity::getAlgorithmTimeOne)));
        Map<String, BigDecimal> longMap = new HashMap<>(4);
        for (Map.Entry<String, LongSummaryStatistics> entry : mapList.entrySet()) {
            longMap.put(entry.getKey(), NumberUtil.getPercent(entry.getValue().getSum(),all));
        }
        return R.ok().put("data", longMap);
    }
    /**
     * 列表
     */
    @PostMapping("/list-collect")
    @ApiOperation("查询链路场景")
    public R collectByDateNew(Long deptId, Date start,Date end){
        SubApplicationEntity subApplicationEntity = subApplicationService.queryByDeptId(deptId);
        Long appId = -1L;
        if(subApplicationEntity!=null){
            appId = subApplicationEntity.getAppId();
        }


        QueryWrapper<SubAppLogCollectEntity> query = new QueryWrapper<SubAppLogCollectEntity>().ge("log_date",start).lt("log_date",end).eq("app_id",appId);
        List<SubAppLogCollectEntity> list = subAppLogCollectService.list(query);
        List<AgentArithmeticStepCollectEntity> stepList = new ArrayList<>();
        list.forEach(a->{
            List<AgentArithmeticStepCollectEntity> step = JSON.parseObject(a.getStepArithPath(), new TypeReference<List<AgentArithmeticStepCollectEntity>>() {});
            stepList.addAll(step);
        });
        Long sum = stepList.stream().mapToLong(AgentArithmeticStepCollectEntity::getAlgoCount).sum();
        Map<String, LongSummaryStatistics> collect = stepList.stream().collect(Collectors.groupingBy(AgentArithmeticStepCollectEntity::getStepAlgo, Collectors.summarizingLong(AgentArithmeticStepCollectEntity::getAlgoCount)));

        Map<String, BigDecimal> longMap = new HashMap<>(4);
        for (Map.Entry<String, LongSummaryStatistics> entry : collect.entrySet()) {
            String key = entry.getKey();
            List<SysDictEntity> sysDictEntities = dictConfig.getSysDictList().get(SysDictConstant.ARITH);
            if(!ObjectUtils.isEmpty(sysDictEntities)){
                for (SysDictEntity sysDictEntity : sysDictEntities) {
                     key = key.replace(sysDictEntity.getValue(), sysDictEntity.getCode());
                     key = key.replace(",","，");
                }
            }
            longMap.put(key, NumberUtil.getPercent(entry.getValue().getSum(),sum));
        }
        return R.ok().put("data", longMap);
    }
    /**
     * 列表
     */
    @PostMapping("/list-collect-last-year")
    @ApiOperation("查询链路场景")
    public R collectByLastYear(Long deptId){
        Date dayFirstDate = io.yuncheng.common.utils.DateUtils.getDayFirstDate(new Date());
        R r = collectByDateNew(deptId, DateUtils.getLastYear(dayFirstDate), dayFirstDate);
        return r;
    }


}
